package com.yami.shop.mystery.common.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.event.CategoryWordEvent;
import com.yami.shop.mystery.common.enums.ActivityEnum;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.model.MysteryBoxExtension;
import com.yami.shop.mystery.common.service.MysteryBoxExtensionService;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wxf
 * @date 2023/4/13 14:43
 */
@Component("categoryMysteryBoxListener")
@Slf4j
@AllArgsConstructor
public class CategoryMysteryBoxListener {

    private final MysteryBoxExtensionService extensionService;

    private final MysteryBoxService mysteryBoxService;

    @EventListener(CategoryWordEvent.class)
    public void categoryMysteryBoxListener(CategoryWordEvent event){
        List<Long> prodIds = event.getProdIdList();
        // 失效秒杀活动
        if(CollUtil.isNotEmpty(prodIds)){
            List<MysteryBoxExtension> extensions = extensionService.list(Wrappers.lambdaUpdate(MysteryBoxExtension.class)
                    .in(MysteryBoxExtension::getPid, prodIds));
            List<Long> boxIds = extensions.stream().map(a -> a.getBid()).distinct().collect(Collectors.toList());

            mysteryBoxService.update(Wrappers.lambdaUpdate(MysteryBox.class).set(MysteryBox::getStatus, ActivityEnum.INVALID.getValue())
                    .in(MysteryBox::getId,boxIds).eq(MysteryBox::getStatus,ActivityEnum.NORMAL.getValue()));
        }
    }
}
